#include "IMessageHandler.h"
#include <unordered_map>
#include <mutex>
#include <iostream>

namespace SeanNetwork {

DefaultMessageHandler::DefaultMessageHandler() {
    // Set up default handler that just prints message info
    m_DefaultHandler = [](std::shared_ptr<NetworkMessage> message) {
        std::cout << "Unhandled message received: ID=" 
                  << message->GetHeader().MessageId 
                  << ", Size=" << message->GetBodySize() << std::endl;
    };
}

DefaultMessageHandler::~DefaultMessageHandler() {
    // Clear all handlers
    std::lock_guard<std::mutex> lock(m_HandlerMutex);
    m_Handlers.clear();
}

bool DefaultMessageHandler::ProcessMessage(std::shared_ptr<NetworkMessage> message) {
    if (!message) {
        return false;
    }
    
    uint32_t messageId = message->GetHeader().MessageId;
    
    std::function<void(std::shared_ptr<NetworkMessage>)> handler;
    
    {
        std::lock_guard<std::mutex> lock(m_HandlerMutex);
        
        // Find handler for this message ID
        auto it = m_Handlers.find(messageId);
        
        if (it != m_Handlers.end()) {
            handler = it->second;
        } else {
            handler = m_DefaultHandler;
        }
    }
    
    // Execute handler if found
    if (handler) {
        try {
            handler(message);
            return true;
        } catch (const std::exception& e) {
            std::cerr << "Error processing message (ID=" << messageId 
                      << "): " << e.what() << std::endl;
            return false;
        }
    }
    
    return false;
}

void DefaultMessageHandler::RegisterHandler(
    uint32_t messageId, 
    std::function<void(std::shared_ptr<NetworkMessage>)> handler) {
    
    if (!handler) {
        return;
    }
    
    std::lock_guard<std::mutex> lock(m_HandlerMutex);
    m_Handlers[messageId] = handler;
}

void DefaultMessageHandler::UnregisterHandler(uint32_t messageId) {
    std::lock_guard<std::mutex> lock(m_HandlerMutex);
    m_Handlers.erase(messageId);
}

} // namespace SeanNetwork 
